package com.bzsg.simpleMediaPlayer.learn

import android.util.Log
import androidx.activity.OnBackPressedCallback
import androidx.activity.compose.LocalOnBackPressedDispatcherOwner
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.requiredSize
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.text.ClickableText
import androidx.compose.foundation.text.selection.SelectionContainer
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.AccountBox
import androidx.compose.material.icons.filled.Info
import androidx.compose.material3.Button
import androidx.compose.material3.Checkbox
import androidx.compose.material3.CheckboxDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.ProgressIndicatorDefaults
import androidx.compose.material3.Slider
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.RectangleShape
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.constraintlayout.compose.ConstraintLayout
import com.bzsg.simpleMediaPlayer.R

const val TAG = "Example"

// chapter2
// Composeable组件都是函数，所有配置来自参数传递，通过参数列表就可以了解组件的所有功能
@Preview(showBackground = true)
@Composable
private fun Demo2(modifier: Modifier = Modifier) {
    LazyColumn {
        item { Text("第一项内容") }
        items(count = 5) { index ->
            Text(text = "第${index}项内容")
        }
        item { Text(text = "最后一项") }
    }
    ConstraintLayout(modifier = Modifier.height(300.dp).width(300.dp)) {
        val portraitImageRef = remember { createRef() }
        Image(
            painter = painterResource(id = R.drawable.ic_launcher_background),
            contentDescription = "null",
            modifier =
                Modifier.constrainAs(portraitImageRef) {
                    top.linkTo(parent.top)
                    bottom.linkTo(parent.bottom)
                    start.linkTo(parent.start)
                },
        )
    }
    val clickTest =
        buildAnnotatedString {
            pushStringAnnotation(tag = "URL", annotation = "test")
            withStyle(style = SpanStyle(fontSize = 24.sp)) {
                append("你现在学习的章节是")
            }
            withStyle(style = SpanStyle(fontSize = 24.sp, fontWeight = FontWeight.W900)) {
                append("text")
            }
        }
    val scrollState = rememberScrollState()
    // 启用垂直滚动
    Column(modifier = Modifier.verticalScroll(scrollState)) {
        Text("helloworld\n" + "Goodbye world", modifier = modifier)
        Text(
            stringResource(R.string.hello_world),
            style =
                TextStyle(
                    fontSize = 25.sp,
                    fontWeight = FontWeight.Bold,
                    background = Color.Cyan,
                    lineHeight = 35.sp,
                ),
        )
        Text(
            stringResource(R.string.hello_world),
            style = TextStyle(color = Color.Gray, letterSpacing = 4.sp),
        )
        Text(
            stringResource(R.string.hello_world),
            style = TextStyle(textDecoration = TextDecoration.LineThrough),
        )
        // 2
        Text(
            stringResource(R.string.hello_world),
            style = MaterialTheme.typography.headlineLarge.copy(fontStyle = FontStyle.Italic),
        )
        // 3
        Text(
            stringResource(R.string.hello_world),
            fontFamily = FontFamily.Cursive,
        )
        // 4
        Text(
            clickTest,
        )
        // 获取点击事件处理
        ClickableText(clickTest) {
            Log.i(TAG, "demo2: ")
        }
        // 5.可以被选中的文字
        SelectionContainer {
            Text("我是可以被复制的文字")
        }
        // 6.7
        var text by remember { mutableStateOf("") }
        TextField(
            value = text,
            onValueChange = {
                text = it
            },
            label = {
                Text("用户名")
            },
            leadingIcon = {
                Icon(imageVector = Icons.Filled.AccountBox, contentDescription = "string")
            },
        )

        // 8
        OutlinedTextField(
            value = text,
            onValueChange = {
                text = it
            },
            label = {
                Text("用户名")
            },
        )
        // 9.
        BasicTextField(
            value = "test",
            onValueChange = {
                text = it
            },
        )

        //
//        Icon(
//            imageVector = ImageVector.vectorResource(id = R.drawable.ic_launcher_background),
//            contentDescription = "矢量图资源",
//            tint = Color.Unspecified       //会被主题色覆盖，需要设置这个 禁用主题色覆盖
//        )
//        Icon(
//            bitmap = ImageBitmap.imageResource(R.drawable.test),
//            contentDescription = "图资源",
//            tint = Color.Unspecified
//        )
//        Icon(
//            painter = painterResource(R.drawable.test),
//            contentDescription = "任意图资源",
//            tint = Color.Unspecified
//        )
//        Icon(
//            imageVector = Icons.Filled.Favorite,
//            contentDescription = "预置图资源",
//        )
//        Button(onClick = {
//            Log.i(TAG, "demo2: 设置点击事件")
//        }) { Text("hello world button")
//         Icon(imageVector = Icons.Filled.Done, contentDescription = "done")
//        }
//        //图标按钮
//        IconButton(onClick = {
//            Log.i(TAG, "demo2: 设置点击事件")
//        }) {
//            Icon(imageVector = Icons.Filled.Done, contentDescription = "done")
//        }
//        // 悬浮按钮
//        FloatingActionButton(onClick = {
//            Log.i(TAG, "悬浮按钮")
//        }) {
//            Icon(imageVector = Icons.Filled.Done, contentDescription = "done")
//        }
//
//        //文字扩展版悬浮按钮
//        ExtendedFloatingActionButton(
//            icon = { Icon(imageVector = Icons.Filled.Done, contentDescription = "done") },
//            text = { Text("添加到我喜欢的") },
//            onClick = {}
//        )
        val checkedState =
            remember {
                mutableStateOf(true)
            }
        Checkbox(
            checked = checkedState.value,
            onCheckedChange = {
                checkedState.value = it
            },
            colors =
                CheckboxDefaults.colors(
                    checkedColor = Color(0xFF0079D3),
                ),
        )
//        Switch(checked = checkedState.value, onCheckedChange = {
//            checkedState.value = it
//        })
        var sliderPosition by remember { mutableStateOf(0F) }
        Text(text = "%.1f".format(sliderPosition * 100) + "%")
        Slider(value = sliderPosition, onValueChange = {
            sliderPosition = it
        })
//        Icon(
//            imageVector = Icons.Filled.Face, // 新增的镜像图标
//            contentDescription = "返回"
//        )
        // DialogSample()
        SurfaceExample()
        BarrierGuidelineExample()
    }
}

@Composable
fun BarrierGuidelineExample() {
    var counter = remember { mutableIntStateOf(1) }
    var (counter1, setcounter) = remember { mutableIntStateOf(1) }
    var counter2 by remember { mutableIntStateOf(1) }
    ConstraintLayout(
        modifier =
            Modifier
                .fillMaxWidth()
                .padding(16.dp)
                .background(Color.LightGray),
    ) {
        val verticalGuideline = createGuidelineFromStart(0.5f)

        // 2. 创建组件引用
        val (button1, button2, text1, text2, barrier) = createRefs()

        // 3. 创建屏障 (Barrier) - 基于两个Text的结束位置
        val endBarrier = createEndBarrier(text1, text2)

        // 4. 组件布局
        Button(
            onClick = {},
            modifier =
                Modifier.constrainAs(button1) {
                    start.linkTo(parent.start)
                    top.linkTo(parent.top)
                },
        ) { Text("按钮1") }

        Button(
            onClick = {},
            modifier =
                Modifier.constrainAs(button2) {
                    start.linkTo(verticalGuideline) // 对齐垂直参考线
                    top.linkTo(button1.bottom, margin = 16.dp)
                },
        ) { Text("按钮2") }

        Text(
            "动态文本内容A",
            modifier =
                Modifier.constrainAs(text1) {
                    start.linkTo(parent.start, margin = 8.dp)
                    top.linkTo(button2.bottom, margin = 24.dp)
                },
        )

        Text(
            "更长的动态文本内容B",
            modifier =
                Modifier.constrainAs(text2) {
                    start.linkTo(parent.start, margin = 8.dp)
                    top.linkTo(text1.bottom, margin = 8.dp)
                },
        )

        // 5. 使用屏障约束的组件
        Text(
            "始终在最长文本右侧",
            color = Color.Red,
            modifier =
                Modifier.constrainAs(barrier) {
                    start.linkTo(endBarrier, margin = 16.dp) // 链接到屏障
                    top.linkTo(text2.top)
                    bottom.linkTo(text2.bottom)
                },
        )
    }
}

@Composable
fun DialogSample() {
    var openDialog = remember { mutableStateOf(true) }
//    val dialogWidth = 200.dp
//    val dialogHeight = 50.dp
//    if (openDialog.value) {
//        Dialog(onDismissRequest = { openDialog.value = false }) {
//            Box(Modifier
//                .size(dialogWidth, dialogHeight)
//                .background(color = Color.White))
//        }
//    }
    // 'AlertDialog' is deprecated. Use BasicAlertDialog instead
//    val dialogWidth = 200.dp
//    val dialogHeight = 50.dp
//    if (openDialog.value) {
//        BasicAlertDialog(onDismissRequest = { openDialog.value = false }) {
//            Box(Modifier
//                .size(dialogWidth, dialogHeight)
//                .background(color = Color.White))
//        }
//    }

    var progress by remember { mutableStateOf(0.1f) }
    val animatedProcess by animateFloatAsState(
        targetValue = progress,
        animationSpec = ProgressIndicatorDefaults.ProgressAnimationSpec,
    )
    Row(modifier = Modifier.border(1.dp, color = Color.Black)) {
        CircularProgressIndicator(
            progress = { animatedProcess },
        )
        Spacer(Modifier.requiredSize(30.dp))
        OutlinedButton(onClick = {
            if (progress < 1f) progress += 0.1f
        }) { }
    }
}

@Composable
fun SurfaceExample() {
    var clickCount by remember { mutableStateOf(0) }

    // 基础 Surface 示例
    Surface(
        modifier =
            Modifier
                .padding(16.dp)
                .fillMaxWidth(),
        shape = MaterialTheme.shapes.medium, // 使用主题定义的形状
        tonalElevation = 4.dp, // 阴影高度
        shadowElevation = 8.dp, // 阴影强度
        color = MaterialTheme.colorScheme.surfaceContainer, // 表面容器颜色
        border = BorderStroke(1.dp, MaterialTheme.colorScheme.outline), // 边框
    ) {
        Column(
            modifier = Modifier.padding(16.dp),
            horizontalAlignment = Alignment.CenterHorizontally,
        ) {
            Text(
                text = "Surface 组件示例",
                style = MaterialTheme.typography.headlineSmall,
            )
            Spacer(modifier = Modifier.height(16.dp))
            Text("点击次数: $clickCount")
            Spacer(modifier = Modifier.height(8.dp))
            Button(onClick = { clickCount++ }) {
                Text("点击我")
            }
        }
    }

    // 卡片式 Surface
    Spacer(modifier = Modifier.height(24.dp))
    Surface(
        modifier =
            Modifier
                .padding(horizontal = 16.dp)
                .fillMaxWidth(),
        shape = MaterialTheme.shapes.large,
        tonalElevation = 8.dp,
    ) {
        Row(
            modifier = Modifier.padding(16.dp),
            verticalAlignment = Alignment.CenterVertically,
        ) {
            Icon(
                imageVector = Icons.Default.Info,
                contentDescription = "信息",
                modifier = Modifier.size(40.dp),
            )
            Spacer(modifier = Modifier.width(16.dp))
            Text(
                text = "这是卡片式Surface示例",
                style = MaterialTheme.typography.bodyLarge,
            )
        }
    }

    // 无边框 Surface (用于内容分组)
    Spacer(modifier = Modifier.height(24.dp))
    Surface(
        modifier =
            Modifier
                .padding(16.dp)
                .fillMaxWidth(),
        shape = RectangleShape, // 矩形无圆角
        color = MaterialTheme.colorScheme.surface, // 基础表面颜色
        tonalElevation = 2.dp,
    ) {
        Column(modifier = Modifier.padding(16.dp)) {
            Text("内容分组示例", style = MaterialTheme.typography.titleMedium)
            Text("使用Surface对相关内容进行视觉分组", style = MaterialTheme.typography.bodyMedium)
        }
    }
}

@Composable
fun BackPressHandler(
    enabled: Boolean = true,
    onBackPressed: () -> Unit,
) {
    val backDispatcher = LocalOnBackPressedDispatcherOwner.current?.onBackPressedDispatcher

    val backCallback =
        remember {
            object : OnBackPressedCallback(enabled) {
                override fun handleOnBackPressed() {
                    onBackPressed()
                }
            }
        }

    DisposableEffect(backDispatcher, enabled) {
        backDispatcher?.addCallback(backCallback) // 注册返回键监听
        backCallback.isEnabled = enabled // 更新启用状态

        onDispose {
            backCallback.remove() // 自动注销监听
        }
    }
}
// 1.
/*
@Composable
fun Text(
    text: String,   //要显示的文字
    modifier: Modifier = Modifier, //修饰符
    color: Color = Color.Unspecified, //颜色
    fontSize: TextUnit = TextUnit.Unspecified,//大小
    fontStyle: FontStyle? = null,   //绘制文本时使用的字体变体
    fontWeight: FontWeight? = null, //文本粗细
    fontFamily: FontFamily? = null, //文本字体
    letterSpacing: TextUnit = TextUnit.Unspecified,//文本间距
    textDecoration: TextDecoration? = null,      //文本修饰，下划线
    textAlign: TextAlign? = null,                //文本对齐方式
    lineHeight: TextUnit = TextUnit.Unspecified, //每行文本的间距
    overflow: TextOverflow = TextOverflow.Clip, //文本溢出时的视觉效果
    softWrap: Boolean = true,                  //文本是否能控制换行
    maxLines: Int = Int.MAX_VALUE,            //
    minLines: Int = 1,
    onTextLayout: ((TextLayoutResult) -> Unit)? = null, //在文本发生变化，回调的处理方法
    style: TextStyle = LocalTextStyle.current   //文字的风格配置
)
 */
// 2. style文字样式
// 3. fontFamily字体风格
// 4. AnnotatedString 多样式文字
// 5.可以被选中的文字
// 6.TextField 输入框
// 7.为输入法框添加装饰
// 8.BasicTextField低级别文本框，可以自己定义更多效果

// 图片组件
// Icon
// 三种不同类型的图片设置
// 矢量图对象
// 位图对象
// 自定义画笔
// https://fonts.google.com/icons图标下载使用
// 扩展使用：androidx-material-icons-extended = { group = "androidx.compose.material", name = "material-icons-extended" }
// Image 和icon支持三种类型的图片设置
// Image 适合数据量比较大的，Icon适合数据量较小

// 按钮按键

// 选择器
// 1. Checkedbox复选框
// 2. TriStateCheckbox 三态复选框
// 3.switch 单选开关
// 4. Slider 滑竿组件

// 对话框
// 1.Dialog
// 2.AlertDialog警告对话框
// 3.进度条

// 线性布局
// 1.Column 垂直布局
// 2.Row    左右布局
// 3.BOX    帧布局
// 4.Surface 帧布局
// 如果我们需要快速设置界面的形状、阴影、边框、颜色等、则用Surface更为合适
// 如果只是需要简单地设置界面的背景颜色、大小、且有时候需要简单地安排里面布局的位置，则用Box
// 5.Spacer 留白
// 6.ConstraintLayout 约束布局
// Barrier引导线
// Guilde分界线
// 7.Scaffold 脚手架

// 列表
